<?php
class Admin extends Admin_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->model("Admin_m");
		$this->_data['sidebar'] = "user";
		$this->load->library('formdate');
		
	}
	
	public function index(){
		$this->users();
	}
	
	public function login(){
		if($this->session->userdata("user_id")!=NULL){
			redirect("admin");
		}
		$config = array(
					    	array("field" => "email",
					    		  "label" => lang("email"),
					    	      "rules" => "required|valid_email|xss_clean"
					    	     ),
					    	     
					    	array("field" => "password",
					    		  "label" => lang("password"),
					    	      "rules" => "required|xss_clean"
					    	     )    	
					    );
		$this->form_validation->set_rules($config);
		if($this->input->post("submit")){
		//form validation true
			if($this->form_validation->run()){
				//check valid email and password
				$email = $this->input->post("email");	
				$password = md5($this->input->post("password"));
				
				$query = $this->Admin_m->_check_valid_login($email, $password);
				$countUser = $query->num_rows();
				
				if($countUser == 1){//valid email and password
					//set session
					$user_infor = $this->Admin_m->_get_user_infor($email)->row();
					if($user_infor->active != 1){
						$_data['login_error'] = "Compte est banni";
						$this->load->view("admin/users/login", $_data);		
					}else{
						$user_id = $user_infor->id;
						$user_name = $user_infor->user_name;
						$role_id = $user_infor->roleid;
						$this->session->set_userdata("user_id", $user_id);
						$this->session->set_userdata("user_name", $user_name);
						$this->session->set_userdata("role_id", $role_id);
						//update last login
						$this->Admin_m->update_last_login(array("last_login"=>now()), $user_id);
						//load admin panel
						redirect("admin");	
					}
				}else{//wrong email or password
					$_data['login_error'] = "Email ou mot de passe est erroné";
					$this->load->view("admin/users/login", $_data);	
				}
				
			}else{
			//form validation fail
			$this->load->view("admin/users/login");	
				
			}
			
			
		}else{
			$this->load->view("admin/users/login");	
		}
	
	}
	
	//--logout--//
	function logout(){
		//check session != null
		//unset session
		//redirect login page
		if($this->session->userdata("user_id") != NULL){
			$this->session->unset_userdata("user_id");
			redirect("admin/login");
		}else{
			redirect("admin/login");
		}
	}
	
	//--list users--//
	public function users(){
		is_admin();
		$this->_data['page_title'] = "users";
		$perpage = $this->uri->segment(3);
		$offset = $this->uri->segment(4);
		if($perpage == ""){
			$perpage = 10; //10 records per page
		}
		if($offset == ""){
			$offset = "";
		}
		$config['base_url'] = base_url()."index.php/admin/users/".$perpage."/";
		$config['per_page'] = $perpage;
		$config['uri_segment'] = 4;
		$config['total_rows'] = $this->Admin_m->_count_users();
		if($offset > 0 && $offset == $config['total_rows']){
			$offset = $offset - $perpage;
		}
		$this->pagination->initialize($config);
    	$this->_data['pagination'] = $this->pagination->create_links();
    	$this->_data['total'] = $config['total_rows'];
    	$this->_data['perpage'] = $perpage;
    	$this->_data['offset'] = $offset;
    	
		$query = $this->Admin_m->_get_users($perpage, $offset);
		$user_data = array();
		foreach($query as $key => $value){
			$user_data[$key] = $value;
			$active = "In-Active";
			if($value['active'] == 1){
				$active = "Active";	
			}
			$user_data[$key]['active'] = $active;
			
			$create_time = unix_to_human($value['created_on']);
			$login_time =  unix_to_human($value['last_login']);
			$user_data[$key]['created_on'] = $create_time;
			$user_data[$key]['last_login'] = $login_time;
		}
		
		$this->_data['users_data'] = $user_data;
		$this->display_admin("admin/users/list_users");	
	}
	
	//--Add new user--//
	public function ajouter_user(){
		is_admin();
		$this->_data['page_title'] = "Ajouter User"; //page title
		//dropdown role
    	$dd_roles = $this->Admin_m->_get_dd_data('role');
    	$this->_data['dd_roles'] = $dd_roles;  
    	
		// validate form config
		$config = array(
							array("field" => "first_name",
							      "label" => lang("first_name"),
								  "rules" => "required|trim|xss_clean"
							      ),
							
							array("field" => "last_name",
							      "label" => lang("last_name"),
								  "rules" => "required|trim|xss_clean"
							      ),
							      							      
							array("field" => "email",
							      "label" => "Email",
								  "rules" => "required|trim|xss_clean|valid_email|callback__check_exist_field[users.email]"
							      ),
							
							array("field" => "user_name",
							      "label" => lang("user_name"),
								  "rules" => "required|trim|xss_clean|callback__check_exist_field[users.user_name]"
							      ),
						
							array("field" => "password",
							      "label" => "Password",
								  "rules" => "required|trim|xss_clean|min_length[5]|callback__check_matches_password"
							      ),
							      
							array("field" => "confirm_password",
							      "label" => "Confirmation du mot de passe",
								  "rules" => "required|trim|xss_clean"
							      ),
							      
							array("field" => "roles",
							      "label" => lang("role"),
								  "rules" => "callback__check_dropdown"
							      ),      
						);
		$this->form_validation->set_rules($config);//set validation rules

		if($this->input->post("submit")){
			//if validate form OK add data to database
			//else re-load form and show errors
			if($this->form_validation->run() === TRUE){
				//Add to user table
				$create_on = now();
				$password = md5($this->input->post("password"));
				$role_id = $this->input->post("roles");
				$query_add_user = $this->Admin_m->add_user(array("password" => $password, 
														"created_on" => $create_on, "role_id"=> $role_id, "active"=>1)
												  );
				if($query_add_user){
					$user_id = $this->Admin_m->_get_insert_id();
					$query_add_user_profile = $this->Admin_m->add_user_profile(array("user_id" => $user_id));
					if($query_add_user_profile){
						$this->session->set_flashdata("error", lang("add"). " ".lang("success"));
						redirect("admin");	
					}else{
						$this->session->set_flashdata("error", lang("add"). " ".lang("fail"));
						redirect("admin");	
					}
					
				}else{
					$this->session->set_flashdata("error", lang("add"). " ".lang("fail"));
					redirect("admin");
				}	
			}else{
				$this->display_admin('admin/users/add_user');	
			}	
		}else{
			$this->display_admin('admin/users/add_user');	
		}
			
	}
	
	//--edit profile--//
	//user only can edit his/her own account
	//user can see but not edit profile of other users
	function modifier_profile($id){
		is_admin();
		$this->_data['page_title'] = "modifier profile";
		$this->load_profile($id, TRUE);

		//validate form config
		$config = array(
														      
							array("field" => "first_name",
							      "label" => lang("first_name"),
								  "rules" => "required|trim|xss_clean"
							      ),
							
							array("field" => "last_name",
							      "label" => lang("last_name"),
								  "rules" => "required|trim|xss_clean"
							      ),
						
							array("field" => "telephone",
							      "label" => lang("telephone"),
								  "rules" => "trim|xss_clean"
							      ),
							      
							array("field" => "telephone",
							      "label" => lang("mobilephone"),
								  "rules" => "trim|xss_clean"
							      ),
							      
							array("field" => "gender",
							      "label" => lang("gender"),
								  "rules" => "trim|xss_clean"
							      ),
							 
				
						);
		$this->form_validation->set_rules($config);//set validation rules
		
		
		//if submit button clicked
		//process form
		//else reload form
			
		if($this->input->post("submit")){
			//validation ok
			if($this->form_validation->run() === TRUE){
				$dob_day = $this->input->post("day");
				$dob_month = $this->input->post("month");
				$dob_year = $this->input->post("year");
				$dob_bigint = mktime("0","0","0", $dob_month, $dob_day, $dob_year);//convert datetime to bigint
				
				$query = $this->Admin_m->edit_user(array("DOB"=>$dob_bigint, "gender"=>$this->input->post("gender")), $id);
				if($query){
					$this->session->set_flashdata("error", lang("edit_profile")." Profile ".lang("success"));
					redirect("admin");
				}else{
					$this->session->set_flashdata("error", lang("edit_profile")." Profile ".lang("fail"));
					redirect("admin");
				}
			}else{//validation false
				$this->display_admin('admin/users/edit_profile');	
			}			
		}else{
			$this->display_admin('admin/users/edit_profile');	
		}
	
	}
	
	//--view user profile--//
	function view_profile($id){
		is_admin();
		$this->_data['page_title'] = "Profile";
		$this->load_profile($id, FALSE);
		$this->display_admin('admin/users/view_profile');
	}
	
	//--load user profile--//
	function load_profile($id, $to_edit = FALSE){
		if(!isset($id) && ($id == NULL) ){
			redirect("admin");	
		}else{
			if($this->Admin_m->_get_user_id($id) === FALSE){
				redirect("admin");	
			}elseif($to_edit === TRUE){
				if($id != $this->session->userdata("user_id")){
				redirect("admin");	
			}
			}
		}
		//load exist data to form
		$profile_data = $this->Admin_m->get_user_profile($id);
		$data = $this->_data['profile_data'] = $profile_data->row();
		
		//load company
		$company = $data->company;
		$this->_data['company'] = $company;
		
		//dropdown companies 
    	$dd_roles = $this->Admin_m->_get_dd_data('company');
    	$this->_data['dd_company'] = $dd_roles;  
    	
    	//create dropdown date time
    	$dob_bigint = $data->DOB;
    	$datestring = "%Y-%m-%d";
    	$dob_arr = mdate($datestring, $dob_bigint);
    	$dob_human= explode("-", $dob_arr);
   		    	
    	$formdate = new FormDate();
		$formdate->setLocale(LC_TIME, 'fr_FR.utf8','fra');
		//year
		$formdate->year['start'] = 1940;
		$formdate->year['end'] = 2040;
		$formdate->year['selected'] = $dob_human[0];
		$formdate->year['extra'] = 'class="short"';
		//month
		$formdate->month['values'] = 'names';
		$formdate->month['selected'] = $dob_human[1];
		$formdate->month['extra'] = 'class="short"';
		//day
		$formdate->day['selected'] = $dob_human[2];
		$formdate->day['extra'] = 'class="short"';
		
		$this->_data['formdate'] = $formdate;	
		
		//gender
		$dd_gender = array("1"=>"male", "2"=>"female");
		$this->_data['dd_gender'] = $dd_gender;
		$gender = $data->gender;
		$this->_data['gender'] = "";
		if($gender == 1){
			$this->_data['gender'] = "Male";
		}elseif($gender == 2){
			$this->_data['gender'] = "FeMale";
		}
		
	}
	
	//--change active status--//
	function changement($id){
		is_admin();
		$active_status = $this->Admin_m->_check_active_status($id)->row();
		if($active_status->active == 1){
			$data = array("active" => 0);
			
		}elseif($active_status->active == 0){
			$data = array("active" => 1);
		}
		$this->Admin_m->update_active_status($data, $id);
		redirect("admin");
	}
	
	//--change password--//
	function change_password($id=null){
		is_admin();
		$this->_data['page_title'] = "Change Password";
		if(!isset($id) && ($id == NULL) ){
			redirect("admin");	
		}else{
			if($this->Admin_m->_get_user_id($id) === FALSE){
				redirect("admin");	
			}elseif($id != $this->session->userdata("user_id")){
				redirect("admin");	
			}
		}
		
		$config = array(
														      
							array("field" => "old_pass",
							      "label" => "Ancien mot de passe",
								  "rules" => "required|trim|xss_clean|callback__check_old_password"
							      ),
							
							array("field" => "password",
							      "label" => "Nouveau mot de passe",
								  "rules" => "required|trim|xss_clean|min_length[5]|callback__check_matches_password"
							      ),
						
							array("field" => "confirm_password",
							      "label" => "Confirmation le nouveau mot de passe",
								  "rules" => "required|trim|xss_clean"
							      )
		
						);
		$this->form_validation->set_rules($config);
		
		if($this->input->post("submit")){
			if($this->form_validation->run()){
				$data = array("password" => md5($this->input->post("password")));
				$query = $this->Admin_m->change_password($data, $id);
				if($query){
					$this->session->set_flashdata("error", "le changement de mot de passe de succès");
					redirect("admin");	
				}else{
					$this->session->set_flashdata("error", "Mot de passe de changement échouent");
					redirect("admin");
				}	
			}else{
				$this->display_admin('admin/users/change_password');	
			}	
		}else{
			$this->display_admin('admin/users/change_password');	
		}
	
	
	
	}

	//--delete user--//
	//only super admin can delete
	function supprimer($id){
		is_admin();
		$this->_data['page_title'] = "Change Password";
		if(!isset($id) && ($id == NULL) ){
			redirect("admin");	
		}else{
			if($this->Admin_m->_get_user_id($id) === FALSE){
				redirect("admin");	
			}elseif($this->session->userdata("role_id") != 1){
				redirect("admin");
			}
			
			$query = $this->Admin_m->delete_user($id);
			if($query){
				$delete_profile = $this->Admin_m->delete_user_profile($id);
				if($delete_profile){
					$this->session->set_flashdata("error", lang("delete")." ".lang("success"));
					redirect("admin");	
				}else{
					$this->session->set_flashdata("error", lang("delete")." ".lang("success"));
					redirect("admin");
				}
				
			}else{
				$this->session->set_flashdata("error", lang("delete")." ".lang("fail"));
				redirect("admin");
			}
		}	
	}
	
	
	
	//check exist field from db
	//if exist return FALSE
	//else return TRUE
	function _check_exist_field($str, $param){
		$arr = explode(".", $param);
		$query = $this->Admin_m->_get_field_input($arr[0], $arr[1], $str);
		if($query){
			$this->form_validation->set_message("_check_exist_field", "existe");
			return FALSE;
		}else{
			return TRUE;
		}
		
	}
	
	function _check_dropdown($str){
		if($str == -1){
			$this->form_validation->set_message("_check_dropdown", "Vous devez choisir le %s");
			return FALSE;
		}else{
			return TRUE;
		}
	}
	
	//check if password = confirm_password
	// = return True
	// != return FALSE
	function _check_matches_password($str){
		$confirm_password = $this->input->post("confirm_password");
		if($str != $confirm_password){
			$this->form_validation->set_message("_check_matches_password", "Le champ Password doit correspondre au champ Confirm Password.");
			return FALSE;
		}else{
			return TRUE;
		}
	}
	
	//check old password
	function _check_old_password($str_password){
		$password = md5($str_password);
		$id = $this->session->userdata("user_id");
		if($this->Admin_m->get_old_password($password, $id)->num_rows()>0){
			return TRUE;
		}else{
			$this->form_validation->set_message("_check_old_password", "Ancien mot de passe est erroné");
			return FALSE;
		}
			
	}
}